package cn.lblbc.myapplication

import android.media.MediaPlayer
import android.os.Bundle
import android.os.CountDownTimer
import android.widget.Button
import android.widget.NumberPicker
import android.widget.ProgressBar
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    private lateinit var timerTextView: TextView
    private lateinit var startButton: Button
    private lateinit var resetButton: Button
    private lateinit var workRadioButton: RadioButton
    private lateinit var shortBreakRadioButton: RadioButton
    private lateinit var modeGroup: RadioGroup
    private lateinit var progressBar: ProgressBar
    private lateinit var minutePicker: NumberPicker
    private lateinit var secondPicker: NumberPicker

    private var countDownTimer: CountDownTimer? = null
    private var isTimerRunning = false
    private var timeLeftInMillis: Long = 0
    private var originalTimeInMillis: Long = 0

    // 默认工作时间25分钟（毫秒）
    private val defaultWorkTimeInMillis: Long = 25 * 60 * 1000
    // 默认短休息时间5分钟（毫秒）
    private val defaultShortBreakTimeInMillis: Long = 5 * 60 * 1000

    private var mediaPlayer: MediaPlayer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initViews()
        setupNumberPickers()
        setListeners()
        resetTimer()
    }

    private fun initViews() {
        timerTextView = findViewById(R.id.timerTextView)
        startButton = findViewById(R.id.startButton)
        resetButton = findViewById(R.id.resetButton)
        workRadioButton = findViewById(R.id.workRadioButton)
        shortBreakRadioButton = findViewById(R.id.shortBreakRadioButton)
        modeGroup = findViewById(R.id.modeGroup)
        progressBar = findViewById(R.id.progressBar)
        minutePicker = findViewById(R.id.minutePicker)
        secondPicker = findViewById(R.id.secondPicker)
    }

    private fun setupNumberPickers() {
        // 设置分钟选择器
        minutePicker.minValue = 0
        minutePicker.maxValue = 60
        minutePicker.value = 25 // 默认25分钟

        // 设置秒钟选择器
        secondPicker.minValue = 0
        secondPicker.maxValue = 59
        secondPicker.value = 0 // 默认0秒
    }

    private fun setListeners() {
        startButton.setOnClickListener {
            if (isTimerRunning) {
                pauseTimer()
            } else {
                startTimer()
            }
        }

        resetButton.setOnClickListener {
            resetTimer()
        }

        modeGroup.setOnCheckedChangeListener { _, checkedId ->
            if (checkedId == R.id.workRadioButton) {
                minutePicker.value = 25
                secondPicker.value = 0
            } else {
                minutePicker.value = 5
                secondPicker.value = 0
            }
            resetTimer()
        }

        // 添加NumberPicker的值变化监听器
        val numberPickerListener = NumberPicker.OnValueChangeListener { _, _, _ ->
            if (!isTimerRunning) {
                updateTimeFromPickers()
            }
        }

        minutePicker.setOnValueChangedListener(numberPickerListener)
        secondPicker.setOnValueChangedListener(numberPickerListener)
    }

    private fun updateTimeFromPickers() {
        val minutes = minutePicker.value
        val seconds = secondPicker.value
        timeLeftInMillis = ((minutes * 60) + seconds) * 1000L
        originalTimeInMillis = timeLeftInMillis
        updateTimerUI()
    }

    private fun startTimer() {
        countDownTimer = object : CountDownTimer(timeLeftInMillis, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                timeLeftInMillis = millisUntilFinished
                updateTimerUI()
                updateProgressBar()
                updatePickersFromTime()
            }

            override fun onFinish() {
                isTimerRunning = false
                startButton.text = getString(R.string.start)
                playAlarmSound()
                resetTimer()
            }
        }.start()

        isTimerRunning = true
        startButton.text = getString(R.string.pause)
    }

    private fun pauseTimer() {
        countDownTimer?.cancel()
        isTimerRunning = false
        startButton.text = getString(R.string.start)
    }

    private fun resetTimer() {
        pauseTimer()
        
        // 从NumberPicker获取时间
        updateTimeFromPickers()
        
        updateTimerUI()
        updateProgressBar()
    }

    private fun updateTimerUI() {
        val minutes = (timeLeftInMillis / 1000) / 60
        val seconds = (timeLeftInMillis / 1000) % 60
        val timeFormatted = String.format("%02d:%02d", minutes, seconds)
        timerTextView.text = timeFormatted
    }

    private fun updatePickersFromTime() {
        val minutes = (timeLeftInMillis / 1000) / 60
        val seconds = (timeLeftInMillis / 1000) % 60
        minutePicker.value = minutes.toInt()
        secondPicker.value = seconds.toInt()
    }

    private fun updateProgressBar() {
        val progress = if (originalTimeInMillis > 0) {
            ((originalTimeInMillis - timeLeftInMillis) * 100 / originalTimeInMillis).toInt()
        } else {
            0
        }
        progressBar.progress = progress
    }

    private fun playAlarmSound() {
        try {
            if (mediaPlayer == null) {
                // 使用系统默认提示音
                mediaPlayer = MediaPlayer.create(this, android.provider.Settings.System.DEFAULT_NOTIFICATION_URI)
            }
            mediaPlayer?.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()
        mediaPlayer?.release()
        mediaPlayer = null
    }
}
